<template>
  <div class="wrapper w-full h-full">
    <canvas id="canvas" />
    <Loading />
    <TipBar />
  </div>
</template>
<script setup lang="ts">
import { CanvasTexture, Color, Scene, Sprite, SpriteMaterial, Vector3 } from "three";
import { onMounted } from "vue";
import Loading from "../components/Loading.vue";
import InitScene from "../utils/InitScene";
import { defaultLoaderModel } from "../utils/LoaderModel";
import TipBar from "../components/TipBar.vue";
import { DefaultSelectOperate } from "../utils/SelectOperate";
import { getTextCanvas } from "../utils/index";
let canvas: HTMLCanvasElement | null;
let scene: Scene;
const defaultInitScene = new InitScene();
const url: string = "animal/scene.gltf";
const tipsSceneName: string[] = [
  "Plane.001_0-犀牛",
  "Plane.003_0-大象",
  "Plane.010_0-羚羊A",
  "Plane.014_0-羚羊B",
  "Plane.002_0-长颈鹿",
  "Plane.005_0-鸵鸟",
  "Plane.008_0-树",
];
onMounted(() => {
  canvas = document.querySelector("#canvas");
  if (!canvas) return;
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  defaultInitScene.init(canvas);
  scene = defaultInitScene.scene;
  scene.background = new Color("#D6D7D8");
  defaultLoaderModel.load(url).addEventListener("loaded", (e) => {
    let { data } = e.data;
    let scene = data.scene;
    scene.scale.set(0.5, 0.5, 0.5);
    scene.traverse((res: any) => {
      if (res.isMesh) {
        tipsSceneName.findIndex((item) => {
          if (item.includes(res.userData.name)) {
            console.log(res);
            let color =
              new Date().getTime() % 2 == 1
                ? "rgba(234,42,6,1)"
                : "rgba(0,0,0,1)";
            let label: Sprite = makeTextSprite(item, {
              color,
            });
            var worldVector = new Vector3();
            res.getWorldPosition(worldVector);
            //世界坐标转标准设备坐标，standardVector是WebGL设备坐标
            var standardVector = worldVector.project(defaultInitScene.camera);
            res.add(label);
          }
        });
      }
    });
    defaultInitScene.scene.add(scene);
  });
  defaultInitScene.renderer.domElement.addEventListener("mousemove", (e) => {
    DefaultSelectOperate.handleMouse(
      e.clientX,
      e.clientY,
      defaultInitScene.camera,
      defaultInitScene.scene
    );
  });
});

function createLabel(name: string) {
  let canvas = getTextCanvas(name);
  if (canvas) {
    const texture = new CanvasTexture(canvas);
    const labelMaterial = new SpriteMaterial({
      map: texture,
      transparent: true,
    });
    const label = new Sprite(labelMaterial);
    label.scale.set(4, 4, 4);
    return label;
  }
}

/* 创建字体精灵 */
function makeTextSprite(message: string, parameters: { [key: string]: any }) {
  if (parameters === undefined) parameters = {};
  let fontface = parameters.hasOwnProperty("fontface")
    ? parameters["fontface"]
    : "Arial";
  /* 字体大小 */
  let fontsize = parameters.hasOwnProperty("fontsize")
    ? parameters["fontsize"]
    : 18;

  let color = parameters.hasOwnProperty("color")
    ? parameters["color"]
    : "rgba(0, 0, 0, 1.0)";
  /* 边框厚度 */
  let borderThickness = parameters.hasOwnProperty("borderThickness")
    ? parameters["borderThickness"]
    : 4;
  /* 边框颜色 */
  let borderColor = parameters.hasOwnProperty("borderColor")
    ? parameters["borderColor"]
    : {
        r: 0,
        g: 0,
        b: 0,
        a: 1.0,
      };
  /* 背景颜色 */
  let backgroundColor = parameters.hasOwnProperty("backgroundColor")
    ? parameters["backgroundColor"]
    : {
        r: 255,
        g: 255,
        b: 255,
        a: 1.0,
      };

  /* 创建画布 */
  let canvas = document.createElement("canvas");
  let context = canvas.getContext("2d");
  if (context) {
    /* 字体加粗 */
    context.font = "Bold " + fontsize + "px " + fontface;
    /* 获取文字的大小数据，高度取决于文字的大小 */
    let metrics = context.measureText(message);
    let textWidth = metrics.width;
    let width = textWidth + borderThickness;
    let height = fontsize * 1.4 + borderThickness;
    /* 背景颜色 */
    context.fillStyle =
      "rgba(" +
      backgroundColor.r +
      "," +
      backgroundColor.g +
      "," +
      backgroundColor.b +
      "," +
      backgroundColor.a +
      ")";
    /* 边框的颜色 */
    context.strokeStyle =
      "rgba(" +
      borderColor.r +
      "," +
      borderColor.g +
      "," +
      borderColor.b +
      "," +
      borderColor.a +
      ")";
    context.lineWidth = borderThickness;
    /* 绘制圆角矩形 */
    roundRect(
      context,
      borderThickness / 2,
      borderThickness / 2,
      width,
height,
      6
    );
    /* 字体颜色 */
    context.fillStyle = color;
    context.fillText(message, borderThickness, fontsize + borderThickness);
    /* 画布内容用于纹理贴图 */
  }
  let texture = new CanvasTexture(canvas);

  texture.needsUpdate = true;
  let spriteMaterial = new SpriteMaterial({
    map: texture,
  });
  let sprite = new Sprite(spriteMaterial);
  /* 缩放比例 */
  sprite.scale.set(10, 5, 0);
  return sprite;
}

/* 绘制圆角矩形 */
function roundRect(
  ctx: any,
  x: number,
  y: number,
  w: number,
  h: number,
  r: number
) {
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.lineTo(x + w - r, y);
  ctx.quadraticCurveTo(x + w, y, x + w, y + r);
  ctx.lineTo(x + w, y + h - r);
  ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
  ctx.lineTo(x + r, y + h);
  ctx.quadraticCurveTo(x, y + h, x, y + h - r);
  ctx.lineTo(x, y + r);
  ctx.quadraticCurveTo(x, y, x + r, y);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
}
</script>
